﻿using System.Diagnostics;
using System.IO;
using System.ServiceModel.Channels;
using System.Text;
using System.Xml;

namespace RockBus.ServiceModel.Diagnostics
{
    public static class MessageLogger
    {
        [Conditional("DEBUG")]
        public static void LogMessage(Message message)
        {
            using (MessageBuffer mb = message.CreateBufferedCopy(4 * 1024 * 1024))
            {
                using (Message copy = mb.CreateMessage())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8))
                        {
                            xtw.Formatting = Formatting.Indented;
                            copy.WriteMessage(xtw);
                            xtw.Flush();

                            ms.Seek(0, SeekOrigin.Begin);
                            using (StreamReader sr = new StreamReader(ms))
                            {
                                string xml = sr.ReadToEnd();
                                Trace.WriteLine(xml);
                            }
                        }
                    }
                }

                message = mb.CreateMessage();
            }
        }
    }
}